<template>
  <div class="forgetpwd">
    <el-form ref="forgetpwdRef" :model="forgetpwdForm" :rules="forgetpwdRules" class="forgetpwd-form">
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="username">
        <el-input v-model="forgetpwdForm.username" type="text" auto-complete="off" placeholder="请输入邮箱" size="large">
          <template #prefix><svg-icon icon-class="email" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="forgetpwdForm.code" auto-complete="off" placeholder="请输入邮箱验证码" style="width: 63%" @keyup.enter="handleForgetpwd" size="large">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="forgetpwd-code">
          <el-button type="info" @click="getVCode" :disabled="sendEmailBtnFlag" plain size="large">{{ sendEmailBtnMsg }}</el-button>
        </div>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="forgetpwdForm.password" type="password" auto-complete="off" placeholder="新密码" @keyup.enter="handleForgetpwd" size="large">
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input v-model="forgetpwdForm.confirmPassword" type="password" auto-complete="off" placeholder="确认密码" @keyup.enter="handleForgetpwd" size="large">
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width:100%;"
          @click.prevent="handleForgetpwd"
        >
          <span v-if="!loading">重置密码</span>
          <span v-else>密码重置 中...</span>
        </el-button>
        <el-row style="width: 100%;">
          <el-col :span="10" :offset="14" style="text-align: right">
            <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <el-dialog title="发送重置密码邮件" :before-close="sendMailClose" v-model="sendEmailFlag" width="400px" style="top: 15%" append-to-body>
      <el-form ref="emailRef" :model="emailForm" :rules="emailRules" label-width="80px" @submit.native.prevent>
        <el-row>
          <el-col :span="14">
            <el-form-item label="验证码" prop="code">
              <el-input v-model="emailForm.code" placeholder="验证码" maxlength="10" @keyup.enter="sendEmail" size="large"/>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="padding-left: 20px;">
            <img :src="codeUrl" @click="getCode" class="forgetpwd-code-img"/>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendEmail" size="large">发送重置密码邮件</el-button>
        <el-button @click="sendMailClose" size="large">取 消</el-button>
      </div>
    </el-dialog>

    <!--  底部  -->
    <div class="el-forgetpwd-footer">
      <span>{{footer1}}<a href="https://beian.miit.gov.cn" target="_blank">{{footer2}}</a></span>
    </div>

  </div>
</template>

<script setup>
import { ElMessageBox } from "element-plus";
import {getCodeImg, forgetpwd, sendEmailPwd} from "@/api/login";

const title=import.meta.env.VITE_APP_TITLE
const footer1=import.meta.env.VITE_APP_FOOTER1
const footer2=import.meta.env.VITE_APP_FOOTER2
const router = useRouter();
const { proxy } = getCurrentInstance();

const sendEmailBtnFlag=ref(false)
const sendEmailBtnTime=ref(0)
const loading=ref(false)
const timer=ref(null)
const sendEmailFlag=ref(false)
const codeUrl=ref("");
const sendEmailBtnMsg=ref("获取验证码");
const forgetpwdForm=ref({
  username: "",
  password: "",
  confirmPassword: "",
  code: "",
  uuid: ""
});
const emailForm=ref({
  username: "",
  code: "",
  uuid: ""
});
const forgetpwdRules=ref({
  username: [
    { required: true, trigger: "blur", message: "请输入您的账号" },
    { min: 2, max: 50, message: '用户账号长度必须介于 5 和 50 之间', trigger: 'blur' },
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"]
    }
  ]
  // password: [
  //   { required: true, trigger: "blur", message: "请输入您的密码" },
  //   { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
  // ],
  // confirmPassword: [
  //   { required: true, trigger: "blur", message: "请再次输入您的密码" },
  //   { required: true, validator: equalToPassword, trigger: "blur" }
  // ]
  // ,
  // code: [
  //   { min: 6, max: 6, message: '邮箱验证码必须是6位数', trigger: 'blur' },
  //   { required: true, trigger: "change", message: "请输入邮箱验证码" }
  // ]
})

const equalToPassword = (rule, value, callback) => {
  if (forgetpwdForm.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
}

const passwordRules=[
  { required: true, trigger: "blur", message: "请输入您的密码" },
  { min: 6, max: 16, message: '密码必须为6-16位字母、数字或‘@’和‘_’组成', trigger: 'blur' }
]

const confirmPasswordRules=[
  { required: true, trigger: "blur", message: "请再次输入您的密码" },
  { required: true, validator: equalToPassword, trigger: "blur" }
]

const codeRules=[
  { min: 6, max: 6, message: '邮箱验证码必须是6位数', trigger: 'blur' },
  { required: true, trigger: "change", message: "请输入邮箱验证码" }
]

const emailRules={
  code: [
    { required: true, trigger: "change", message: "请输入验证码" }
  ]
}

function getCode() {
  getCodeImg().then(res => {
    codeUrl.value = "data:image/gif;base64," + res.data.img;
    emailForm.value.uuid = res.data.uuid;
  });
}

function sendMailClose(){
  sendEmailFlag.value=false;
}

function timers() {
  timer.value = setInterval(() => {
    if (sendEmailBtnTime.value <= 0) {
      sendEmailBtnFlag.value=false;
      sendEmailBtnMsg.value="获取验证码"
      clearInterval(timer.value)
    }else{
      const msg=sendEmailBtnTime.value+"秒后重发";
      sendEmailBtnTime.value=sendEmailBtnTime.value-1;
      sendEmailBtnMsg.value=msg;
    }
  }, 1000)
}

function sendEmail(){
  proxy.$refs.emailRef.validate(valid =>{
    if(valid){
      sendEmailPwd(emailForm.value).then(res => {
        sendMailClose();
        proxy.$modal.msgSuccess("邮件发送成功！");
        forgetpwdForm.value.uuid=res.data.uuid

        sendEmailBtnFlag.value=true
        sendEmailBtnTime.value=60
        timers()
      }).catch(err => {
        if(err.code===500002 || err.code===500003){
          sendMailClose();
        } else {
          getCode();
        }
      })
    }
  })
}

function getVCode() {
  proxy.$refs.forgetpwdRef.clearValidate("code")
  proxy.$refs.forgetpwdRef.clearValidate("password")
  proxy.$refs.forgetpwdRef.clearValidate("confirmPassword")
  forgetpwdRules.value.code=null;
  forgetpwdRules.value.password=null;
  forgetpwdRules.value.confirmPassword=null;
  emailForm.value.code="";
  proxy.$refs.forgetpwdRef.validate(valid => {
    if (valid) {
      sendEmailFlag.value = true;
      getCode();
      emailForm.value.username=forgetpwdForm.value.username;
    }else {
      sendEmailFlag.value = false;
    }
  });
}
function handleForgetpwd() {
  forgetpwdRules.value.code=codeRules;
  forgetpwdRules.value.password=passwordRules;
  forgetpwdRules.value.confirmPassword=confirmPasswordRules;
  proxy.$refs.forgetpwdRef.validate(valid => {
    if (valid) {
      loading.value = true;
      forgetpwd(forgetpwdForm.value).then(res => {
        const username = forgetpwdForm.value.username;
        ElMessageBox.alert("<font color='red'>恭喜你，您的账号 " + username + " 密码重置成功！</font>", "系统提示", {
          dangerouslyUseHTMLString: true,
          type: "success",
        }).then(() => {
          router.push("/login");
        }).catch(() => {});
      }).catch(() => {
        loading.value = false;
        getCode();
      })
    }
  });
}
</script>

<style rel="stylesheet/scss" lang="scss">
.forgetpwd {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.webp");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.forgetpwd-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.forgetpwd-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.forgetpwd-code {
  width: 33%;
  height: 38px;
  padding-left: 20px;
}
.el-forgetpwd-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.forgetpwd-code-img {
  height: 38px;
}
</style>
